import { useState, useEffect, useRef, useCallback } from 'react'
import { MessageCircle, Sparkles } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { useFloatingAIConfig } from '../hooks/useFloatingAIConfig'
import { useResponsive } from '../hooks/useResponsive'

export default function FloatingAIBall() {
  const [isDragging, setIsDragging] = useState(false)
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 })
  const navigate = useNavigate()
  const ballRef = useRef<HTMLDivElement>(null)

  // 使用配置hook
  const { config, isLoaded, updatePosition } = useFloatingAIConfig()
  const { isDesktop } = useResponsive()
  const position = config.position

  // 智能避让功能
  const getOptimalPosition = useCallback(() => {
    if (!ballRef.current) return

    const ballRect = ballRef.current.getBoundingClientRect()
    const viewport = {
      width: window.innerWidth,
      height: window.innerHeight
    }

    let newX = position.x
    let newY = position.y

    // 检测底部导航栏
    const bottomNav = document.querySelector('nav[class*="fixed"]')
    if (bottomNav) {
      const navRect = bottomNav.getBoundingClientRect()
      if (newY + ballRect.height > navRect.top - 10) {
        newY = navRect.top - ballRect.height - 20
      }
    }

    // 检测顶部导航栏
    const topNav = document.querySelector('header[class*="fixed"], nav[class*="fixed"]:not([class*="bottom"])')
    if (topNav) {
      const topRect = topNav.getBoundingClientRect()
      if (newY < topRect.bottom + 10) {
        newY = topRect.bottom + 20
      }
    }

    // 边界检测
    newX = Math.max(10, Math.min(newX, viewport.width - ballRect.width - 10))
    newY = Math.max(10, Math.min(newY, viewport.height - ballRect.height - 10))

    return { x: newX, y: newY }
  }, [position])

  // 拖拽处理 - 鼠标事件
  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault()
    setIsDragging(true)
    setDragStart({
      x: e.clientX - position.x,
      y: e.clientY - position.y
    })
  }

  // 拖拽处理 - 触摸事件
  const handleTouchStart = (e: React.TouchEvent) => {
    e.preventDefault()
    const touch = e.touches[0]
    setIsDragging(true)
    setDragStart({
      x: touch.clientX - position.x,
      y: touch.clientY - position.y
    })
  }

  const handleMouseMove = useCallback((e: MouseEvent) => {
    if (!isDragging) return

    const newX = e.clientX - dragStart.x
    const newY = e.clientY - dragStart.y

    updatePosition({ x: newX, y: newY })
  }, [isDragging, dragStart, updatePosition])

  const handleTouchMove = useCallback((e: TouchEvent) => {
    if (!isDragging) return
    e.preventDefault()

    const touch = e.touches[0]
    const newX = touch.clientX - dragStart.x
    const newY = touch.clientY - dragStart.y

    updatePosition({ x: newX, y: newY })
  }, [isDragging, dragStart, updatePosition])

  const handleMouseUp = useCallback(() => {
    if (isDragging) {
      setIsDragging(false)
      // 拖拽结束后进行智能避让
      const optimalPos = getOptimalPosition()
      if (optimalPos) {
        updatePosition(optimalPos)
      }
    }
  }, [isDragging, getOptimalPosition, updatePosition])

  const handleTouchEnd = useCallback(() => {
    if (isDragging) {
      setIsDragging(false)
      // 拖拽结束后进行智能避让
      const optimalPos = getOptimalPosition()
      if (optimalPos) {
        updatePosition(optimalPos)
      }
    }
  }, [isDragging, getOptimalPosition, updatePosition])

  // 点击处理 - 直接打开对话页面
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    if (isDragging) return

    // 直接导航到对话页面
    navigate('/chat')
  }

  // 触摸点击处理
  const handleTouchClick = (e: React.TouchEvent) => {
    e.stopPropagation()
    if (isDragging) return

    // 直接导航到对话页面
    navigate('/chat')
  }


  // 事件监听
  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)
      document.addEventListener('touchmove', handleTouchMove, { passive: false })
      document.addEventListener('touchend', handleTouchEnd)
      return () => {
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
        document.removeEventListener('touchmove', handleTouchMove)
        document.removeEventListener('touchend', handleTouchEnd)
      }
    }
  }, [isDragging, handleMouseMove, handleMouseUp, handleTouchMove, handleTouchEnd])

  // 窗口大小变化时重新定位
  useEffect(() => {
    const handleResize = () => {
      const optimalPos = getOptimalPosition()
      if (optimalPos) {
        updatePosition(optimalPos)
      }
    }

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [getOptimalPosition])


  // 如果未加载配置或未启用，不显示
  if (!isLoaded || !config.isEnabled) return null

  // 桌面端默认位置调整
  const defaultPosition = isDesktop 
    ? { x: window.innerWidth - 100, y: 100 } 
    : { x: 20, y: 20 }

  const currentPosition = position.x === 20 && position.y === 20 && isDesktop 
    ? defaultPosition 
    : position

  return (
    <div
      ref={ballRef}
      className="fixed z-50 transition-all duration-300 ease-out w-10 h-10"
      style={{ 
        left: currentPosition.x, 
        top: currentPosition.y,
        transform: isDragging ? 'scale(1.1)' : 'scale(1)'
      }}
    >
      <button
        onClick={handleClick}
        onMouseDown={handleMouseDown}
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchClick}
        className="w-10 h-10 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 rounded-full shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105 flex items-center justify-center group relative touch-manipulation"
      >
        <MessageCircle size={16} className="text-white group-hover:scale-110 transition-transform" />
        
        {/* AI标识 */}
        <div className="absolute -top-0.5 -right-0.5 w-3 h-3 bg-red-500 rounded-full flex items-center justify-center shadow-md">
          <Sparkles size={6} className="text-white" />
        </div>
      </button>
    </div>
  )
}
